package com.zusmart.base.network.handler.support;

import java.io.IOException;

import com.zusmart.base.buffer.Buffer;
import com.zusmart.base.network.ChannelContext;
import com.zusmart.base.network.handler.ChannelContextHandlerContext;
import com.zusmart.base.network.message.Message;
import com.zusmart.base.network.message.MessageProtocol;

public class DefaultRecognizeHandler extends DefaultChannelContextHandler{

	public static final String NAME = "__AUTO_RECOGNIZE__";

	private final MessageProtocol messageProtocol;

	public DefaultRecognizeHandler(MessageProtocol messageProtocol) {
		this.messageProtocol = messageProtocol;
	}
	
	@Override
	public void onReader(ChannelContext channelContext, ChannelContextHandlerContext handlerContext, Buffer buffer) throws IOException {
		while (buffer.hasRemaining()) {
			Buffer slice = buffer.asReadOnlyBuffer().slice();
			try {
				Message message = this.messageProtocol.decode(slice);
				if (null == message) {
					break;
				}
				buffer.skip(slice.position());
				handlerContext.getChain().fireOnMessage(message);
			} catch (Exception e) {
				handlerContext.getChain().fireOnException(e);
			}
		}
	}
	
}